#include "licenseplaterecognizer.h"
#include <QNetworkRequest>
#include <QUrl>
#include <QJsonDocument>
#include <QJsonObject>
#include <QBuffer>
#include <QDebug>
#include <QUrlQuery>

LicensePlateRecognizer::LicensePlateRecognizer(QObject *parent)
    : QObject(parent),
      m_networkManager(new QNetworkAccessManager(this)),
      m_isGettingToken(false)
{
    // 连接网络请求完成信号
    connect(m_networkManager, &QNetworkAccessManager::finished,
            this, &LicensePlateRecognizer::handleNetworkReply);
}

LicensePlateRecognizer::~LicensePlateRecognizer()
{
    // 释放网络管理器
    m_networkManager->deleteLater();
}

void LicensePlateRecognizer::setCredentials(const QString &apiKey, const QString &secretKey)
{
    // 设置API凭证
    m_apiKey = apiKey;
    m_secretKey = secretKey;
    // 获取访问令牌
    getAccessToken();
}

void LicensePlateRecognizer::recognizeLicensePlate(const QImage &image)
{
    // 检查访问令牌是否可用
    if (m_accessToken.isEmpty())
    {
        emit recognitionError(tr("Access token is not available"));
        return;
    }

    // 检查图片是否有效
    if (image.isNull())
    {
        emit recognitionError(tr("Invalid image"));
        return;
    }

    // 将图片转换为Base64
    QString base64Image = imageToBase64(image);
    if (base64Image.isEmpty())
    {
        emit recognitionError(tr("Failed to convert image to base64"));
        return;
    }

    // 构造请求URL
    QUrl url("https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate?access_token=" + m_accessToken);
    QNetworkRequest request(url);

    // 设置请求头
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    // 构造POST数据
    QByteArray postData;
    postData.append("image=" + QUrl::toPercentEncoding(base64Image));

    // 发送网络请求
    m_networkManager->post(request, postData);
}

QImage LicensePlateRecognizer::loadImage(const QString &filePath)
{
    // 从文件加载图片
    QImage image;
    if (!image.load(filePath))
    {
        qWarning() << "Failed to load image:" << filePath;
        return QImage();
    }
    return image;
}

void LicensePlateRecognizer::getAccessToken()
{
    // 检查API凭证是否设置
    if (m_apiKey.isEmpty() || m_secretKey.isEmpty())
    {
        emit recognitionError(tr("API credentials not set"));
        return;
    }

    m_isGettingToken = true;

    // 构造获取token的URL
    QUrl url("https://aip.baidubce.com/oauth/2.0/token");
    QUrlQuery query;
    query.addQueryItem("grant_type", "client_credentials");
    query.addQueryItem("client_id", m_apiKey);
    query.addQueryItem("client_secret", m_secretKey);

    // 设置请求头
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    // 发送网络请求
    m_networkManager->post(request, query.toString(QUrl::FullyEncoded).toUtf8());
}

QString LicensePlateRecognizer::imageToBase64(const QImage &image)
{
    // 将QImage转换为Base64字符串
    QByteArray byteArray;
    QBuffer buffer(&byteArray);
    buffer.open(QIODevice::WriteOnly);
    if (!image.save(&buffer, "JPEG"))
    {
        qWarning() << "Failed to save image to buffer";
        return QString();
    }
    return byteArray.toBase64();
}

void LicensePlateRecognizer::handleNetworkReply(QNetworkReply *reply)
{
    // 确保reply对象被删除
    reply->deleteLater();

    // 检查网络错误
    if (reply->error() != QNetworkReply::NoError)
    {
        emit recognitionError(reply->errorString());
        return;
    }

    // 读取响应数据
    QByteArray responseData = reply->readAll();
    QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);
    if (jsonDoc.isNull())
    {
        emit recognitionError(tr("Invalid JSON response"));
        return;
    }

    QJsonObject jsonObj = jsonDoc.object();

    // 处理获取token的响应
    if (m_isGettingToken)
    {
        m_isGettingToken = false;
        if (jsonObj.contains("error"))
        {
            emit recognitionError(jsonObj["error_description"].toString());
            return;
        }
        m_accessToken = jsonObj["access_token"].toString();
        return;
    }

    // 处理识别错误
    if (jsonObj.contains("error_code"))
    {
        emit recognitionError(jsonObj["error_msg"].toString());
        return;
    }

    // 提取识别结果
    QString plateNumber = jsonObj["words_result"].toObject()["number"].toString();
    QString color = jsonObj["words_result"].toObject()["color"].toString();

    // 保存车牌号
    m_CarNumber = plateNumber;

    qDebug()<<"已保存车牌号"<<m_CarNumber;

    // 发射识别完成信号
    emit recognitionCompleted(plateNumber, color);
}

// 返回车牌号
QString LicensePlateRecognizer::carNumber()
{
    return m_CarNumber;
}
